using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace Super
{
	public static class EncryptUtil
	{
		/// <summary>
		/// 获取RSA加密的密钥对
		/// </summary>
		public static (string publicKey, string privateKey) GetRSAKeyPairToXmlString()
		{
			RSACryptoServiceProvider rSA = new RSACryptoServiceProvider();

			string publicKeyStr = rSA.ToXmlString(false);
			string privateKeyStr = rSA.ToXmlString(true);

			return (publicKeyStr, privateKeyStr);
		}

		/// <summary>
		/// Debug 以Xml文本格式输出RSA的公钥，私钥
		/// </summary>
		public static void LogRSAKeyPairToXmlString()
		{
			RSACryptoServiceProvider rSA = new RSACryptoServiceProvider();

			string publicKeyStr = rSA.ToXmlString(false);
			string privateKeyStr = rSA.ToXmlString(true);

			Debug.Log($"publicKey:\n{publicKeyStr}");
			Debug.Log($"privateKey:\n{privateKeyStr}");
		}

		/// <summary>
		/// RSA加密算法
		/// </summary>
		/// <param name="text">加密文本</param>
		/// <param name="publicKey">RAS公钥 Xml格式文本</param>
		/// <returns></returns>
		public static string Encrypt(string text, string publicKey)
		{
			byte[] encryptedBytes;

			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			rsa.FromXmlString(publicKey);
			byte[] textBytes = Encoding.UTF8.GetBytes(text);
			encryptedBytes = rsa.Encrypt(textBytes, true);

			return Convert.ToBase64String(encryptedBytes);
		}

		/// <summary>
		/// RSA解密算法
		/// </summary>
		/// <param name="encryptedText">密文文本</param>
		/// <param name="privateKey">私钥 xml文本格式</param>
		/// <returns></returns>
		public static string Decrypt(string encryptedText, string privateKey)
		{
			byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
			byte[] decryptedBytes;

			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			rsa.FromXmlString(privateKey);
			decryptedBytes = rsa.Decrypt(encryptedBytes, true);

			return Encoding.UTF8.GetString(decryptedBytes);
		}
	}
}

